package com.blue.http.filter;

import com.blue.core.auth.CaptchaUtil;
import com.blue.core.dict.HttpMethod;
import com.blue.http.config.ErrorConfig;
import com.blue.http.message.HttpRequest;
import com.blue.http.message.HttpResponse;
import com.blue.http.message.HttpSession;
import com.blue.http.util.HttpException;

import javax.annotation.Resource;

/**
 * 验证码过滤器
 *
 * @author Jin Zheng
 * @date 2018-10-30
 */
public class CaptchaFilter implements Filter
{
	@Resource
	private HttpSession httpSession;

	private String name;
	private ErrorConfig errorConfig = ErrorConfig.getInstance();

	public CaptchaFilter()
	{
	}

	@Override
	public boolean preHandle(HttpRequest request, HttpResponse response) throws HttpException
	{
		if (request.getHttpMethod() == HttpMethod.GET)
			return true;

		String captcha = (String) httpSession.getAttribute(request, CaptchaUtil.SESSION_KEY);
		String value = request.getPost(name);
		if (value == null || value.isEmpty() || !value.equals(captcha))
		{
			response.setCode(ErrorConfig.ERROR_VERIFY);
			response.setMsg(errorConfig.get(ErrorConfig.ERROR_VERIFY));
			return false;
		}

		return true;
	}

	public void setName(String name)
	{
		this.name = name;
	}
}
